<template>
  <div class="treeSelector" :style="{width}">
    <div class="head-container">
      <slot name="header"></slot>
      <div class="title">{{title}}</div>
      <el-input
        v-model="filterKeyword"
        placeholder="请输入关键字"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div class="tree-wrap">
      <el-tree
        :key="forceUpdateKey"
        :data="options"
        :props="treeProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="tree"
        @node-click="clickNode"
        highlight-current
        :node-key="nodeKey"
        :default-expanded-keys="defaultExpandedKeys"
        :current-node-key="currentNodeKey"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "TreeSelector",
  props: {
    title:{
      type: String,
      default: ""
    },
    width: String,
    // 树级数据
    options: {
      type: Array,
      default() {
        return []
      }
    },
    // 树选择器配置
    treeProps: {
      type: Object,
      default() {
        return {
          children: 'children',
          label: 'name'
        }
      }
    },
    // 每个树节点唯一标识的属性，
    nodeKey:{
      type: String,
      default: 'id'
    },
    // 默认展开的节点的 key 的数组
    defaultExpandedKeys:{
      type: Array,
      default() {
        return []
      }
    },
    // 当前选中的节点
    currentNodeKey:{
      type: [Number,String],
    },
  },

  data() {
    return {
      filterKeyword: '',
      forceUpdateKey: Math.random(),
    }
  },
  watch: {
    filterKeyword(newValue) {
      this.$refs.tree.filter(newValue);
    },
    options(){
      // 重新渲染tree才能显示默认激活节点
      this.forceUpdateKey = Math.random();
    }
  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data[this.treeProps.label].indexOf(value) !== -1;
    },
    clickNode(data) {
      this.$emit("click-node",data)
    }
  },
}
</script>

<style lang="scss" scoped>
.treeSelector {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 250px;
  max-height: calc(100vh - 124px);
  min-width: 250px;
  padding: 10px;
  margin-right: 15px;
  border: 1px solid #dfe4ed;
  border-radius: 4px;
  overflow: hidden;

  .title {
    margin-bottom: 10px;
    font-size: 14px;
    color: #606266;
    font-weight: bold;
  }

  .tree-wrap {
    width: 100%;
    flex: 1;
    overflow-y: auto;
  }
}

 ::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
  background: #409eff42;
 }
</style>
